package com.runchinaup.sifitbledome.ble;

import android.bluetooth.BluetoothGatt;
import android.bluetooth.BluetoothGattCharacteristic;
import android.content.Context;
import android.util.Log;

import com.runchinaup.sifitbledome.ble.conn.AbsConn;
import com.runchinaup.sifitbledome.ble.conn.ConnResult;
import com.runchinaup.sifitbledome.ble.conn.NotificationType;
import com.runchinaup.sifitbledome.domain.BleData;
import com.runchinaup.sifitbledome.domain.SendData;

import java.util.UUID;

/**
 * Created by liber on 2018/3/15.
 */

public class BleHelper {

    private UUID serviceUUID = UUID.fromString("c3e6fea0-e966-1000-8000-be99c223df6a");
    private UUID notifyUUID = UUID.fromString("c3e6fea2-e966-1000-8000-be99c223df6a");
    private UUID characteristicUUID = UUID.fromString("c3e6fea1-e966-1000-8000-be99c223df6a");

    private static BleHelper bleHelper = new BleHelper();

    public static BleHelper getBleHelper() {
        return bleHelper;
    }

    private AbsConn absConn = null;
    private boolean isConn = false;

    private BluetoothGatt gatt = null;
    private BluetoothGattCharacteristic characteristic = null;

    //连接蓝牙设备
    public void connDevice(BleData bleData, Context context) {
        if (absConn == null) {
            initConn(bleData);
        }
        if (!isConn) {
            absConn._conn_(bleData.getAdress(), context);
        }
    }

    //自动断开连接
    public void disConn() {
        if (absConn != null) {
            absConn._dis_conn();
        }
    }

    //发送数据
    public void sendData(SendData sendData) {
        byte[] data = new byte[]{sendData.getOne(), sendData.getTwo(),
                sendData.getThree(), sendData.getCommend(),
                sendData.getKey()
        };

        byte[] length = sendData.getLength();
        byte[] getValue = sendData.getValue();

        byte[] value = new byte[data.length + length.length + getValue.length];

        System.arraycopy(data, 0, value, 0, data.length);
        System.arraycopy(length, 0, value, data.length, length.length);
        System.arraycopy(getValue, 0, value, data.length + length.length, getValue.length);

        StringBuilder sb = new StringBuilder();
        for (byte b : value) {
            sb.append(String.format("%02x", b));
        }
        Log.e("debug_ble_data", sb.toString());

        if (gatt != null) {
            if (characteristic != null) {
                characteristic.setValue(value);
                gatt.writeCharacteristic(characteristic);
            }
        }

    }

    //初始化蓝牙回调
    private void initConn(final BleData bleData) {

        absConn = new AbsConn() {
            @Override
            public void onConnectResult(ConnResult connResult) {
                isConn = connResult == ConnResult.CONN_SUCCESS;
                if (bleListener != null) {
                    bleListener.onConnectResult(connResult);
                }
            }

            @Override
            public void onLoadCharacteristic(BluetoothGatt gatt) {

                BluetoothGattCharacteristic characteristic1 = gatt.getService(serviceUUID).getCharacteristic(notifyUUID);
                //开启安卓本地通知  设置监听，然后onChange（）才能接受来自蓝牙的数据
                gatt.setCharacteristicNotification(characteristic1, true);
                //开启ble设备周边通知  打开蓝牙发送通知的开关
                _enable_notify_(gatt, characteristic1, NotificationType.NOTIFICATION);
                //获得读写的特征
                characteristic = gatt.getService(serviceUUID).getCharacteristic(characteristicUUID);
                BleHelper.this.gatt = gatt;

            }

            @Override
            public void onChanged(BluetoothGattCharacteristic characteristic) {
                byte[] data = characteristic.getValue();
                if (bleListener != null) {
                    bleListener.onRecevieData(data);

                    StringBuilder sb = new StringBuilder();
                    for (byte b : data) {
                        sb.append(String.format("%02x", (b & 0xff)));
                    }
                    Log.e("debug_change", sb.toString());
                } else {
                    Log.e("debug_change", "is null");
                }
            }
        };
    }

    private BleListener bleListener;

    public void registerBleListener(BleListener bleListener) {
        this.bleListener = bleListener;
    }

    //监听数据的回调
    public static interface BleListener {

        void onConnectResult(ConnResult connResult);

        void onRecevieData(byte[] data);

    }


}
